﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Exam.DBHelper
{
    public class Tools
    {
        /// <summary>
        /// 通过DataTable设置对象中的属性
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="dt"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        public static T SetPropertyValue<T>(DataTable dt, int i) where T : new()
        {
            T typeClass = new T();
            if (dt.Rows.Count == 0) { return typeClass; }
            PropertyInfo[] propertyInfo = typeof(T).GetProperties();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                foreach (PropertyInfo p in propertyInfo)
                {
                    if (dt.Columns[j].ColumnName.Equals(p.Name) && dt.Rows[i][j] != null)
                    {
                        if (p.PropertyType.ToString().Equals("System.Nullable`1[System.Double]") || p.PropertyType.ToString().Equals("System.Double"))
                        {
                            double d = 0;
                            if (double.TryParse(Convert.ToString(dt.Rows[i][j]), out d))
                            {
                                p.SetValue(typeClass, d);
                            }
                        }
                        else if (p.PropertyType.ToString().Equals("System.Nullable`1[System.Int32]") || p.PropertyType.ToString().Equals("System.Int32"))
                        {
                            int num = 0;
                            if (int.TryParse(Convert.ToString(dt.Rows[i][j]), out num))
                            {
                                p.SetValue(typeClass, num);
                            }
                        }
                        else if (p.PropertyType.ToString().Equals("System.Nullable`1[System.DateTime]") || p.PropertyType.ToString().Equals("System.DateTime"))
                        {
                            DateTime time = new DateTime();
                            if (DateTime.TryParse(Convert.ToString(dt.Rows[i][j]), out time))
                            {
                                p.SetValue(typeClass, time);
                            }
                        }
                        else if (p.PropertyType.ToString().Equals("System.Nullable`1[System.Guid]") || p.PropertyType.ToString().Equals("System.Guid"))
                        {
                            Guid guid = new Guid();
                            if (Guid.TryParse(Convert.ToString(dt.Rows[i][j]), out guid))
                            {
                                p.SetValue(typeClass, guid);
                            }
                        }
                        else
                        {
                            p.SetValue(typeClass, dt.Rows[i][j].ToString());
                        }
                    }
                }
            }

            return typeClass;
        }

        public static List<T> SetPropertyValue<T>(DataTable dt) where T : new()
        {
            try
            {
                List<T> listClass = new List<T>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    T typeClass = new T();
                    typeClass = SetPropertyValue<T>(dt, i);
                    listClass.Add(typeClass);
                }

                return listClass;
            }
            catch { throw; }
        }

        /// <summary>
        /// 通过对象设置对象中的属性
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T SetPropertyValue<T>(T t, ref T t1) where T : new()
        {
            T typeClass = new T();

            PropertyInfo[] propertyInfo = typeof(T).GetProperties();
            foreach (PropertyInfo p in propertyInfo)
            {
                if (typeof(T).GetProperty(p.Name).GetValue(t) != null)
                {
                    if (p.PropertyType.Name.Equals("Nullable`1"))
                    {
                        //if (typeof(T).GetProperty(p.Name).GetValue(t) != null)
                        //{
                        //    p.SetValue(t1, typeof(T).GetProperty(p.Name).GetValue(t));
                        //}
                        DateTime time = new DateTime();
                        int num = 0;
                        if (DateTime.TryParse(Convert.ToString(typeof(T).GetProperty(p.Name).GetValue(t)), out time))
                        {
                            p.SetValue(typeClass, time);
                        }
                        else if (int.TryParse(Convert.ToString(typeof(T).GetProperty(p.Name).GetValue(t)), out num))
                        {
                            p.SetValue(typeClass, num);
                        }
                    }
                    else
                    {
                        p.SetValue(t1, typeof(T).GetProperty(p.Name).GetValue(t));
                    }
                }
            }

            return typeClass;
        }

        public static void SetPropertyNullValue<T>(ref T t)
        {
            PropertyInfo[] propertyInfo = typeof(T).GetProperties();
            foreach (PropertyInfo p in propertyInfo)
            {
                if (p.PropertyType == typeof(String))
                {
                    if (typeof(T).GetProperty(p.Name).GetValue(t) == null)
                    {
                        p.SetValue(t, "");
                    }
                }
            }
        }

        /// <summary>
        /// JSON反序列化，将Json字符串转为类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string strJson)
        {
            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
                T obj = (T)ser.ReadObject(ms);
                return obj;
            }
            catch { throw; }
        }

        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        public static string DataBaseToHtml(string s)
        {
            return s.Replace("\r\n", "<br />").Replace("\n", "<br />");
        }

        public static List<string> RemoveRepeated(string[] arrStr)
        {
            try
            {
                bool flag = false;
                List<string> newList = new List<string>();
                for (int i = 0; i < arrStr.Length; i++)
                {
                    flag = false;
                    for (int j = 0; j < newList.Count; j++)
                    {
                        if (arrStr[i].Equals(newList[j]))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        newList.Add(arrStr[i]);
                    }
                }

                return newList;
            }
            catch
            {

                throw;
            }
        }

        public static List<string> RemoveRepeated(List<string> list)
        {
            try
            {
                return RemoveRepeated(list.ToArray());
            }
            catch
            {

                throw;
            }
        }

        public static void GetStartAndEndRows(int page, int totalCount, int rowPerPage, out int totalPage, out int start, out int end)
        {
            start = 0; end = 0;
            totalPage = (totalCount - 1) / rowPerPage + 1;
            if (page > totalPage) { return; }
            start = rowPerPage * (page - 1) + 1;
            end = rowPerPage * page;
        }

        /// <summary>
        /// 加密password
        /// </summary>
        /// <param name=""></param>
        public static string EncodePassword(string password)
        {
            string highPassword = "K(#&DP_#%!1.";
            string encodePassword = "";
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                encodePassword = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(highPassword))) + BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(password)));
                encodePassword = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(encodePassword)));
            }

            return encodePassword;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name=""></param>
        public static string GetCheckCode()
        {
            string checkCode = "";
            string allCharacter = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            string[] allCharArray = allCharacter.Split(',');
            Random ran = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < 6; i++)
            {
                int index = ran.Next(61);
                checkCode += allCharArray[index];
            }

            return checkCode;
        }

    }
}
